﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;

namespace GUI.KhuyenMaiHangHoa
{
    public partial class frmXuLy : Form
    {
        #region Contructors 

        public bool kiemtra1 = false;
        bool checkClose = false;
        bool check = false;
        string hanhdong;

        Entities.ChinhSachGiaHangHoa chinhsachgiahanghoa;
        Entities.ChinhSachGiaHangHoa temp;
        Entities.ChinhSachGiaHangHoa[] tempcheck;

        Entities.ChiTietChinhSachGiaHangHoa[] chitietchinhsachgiahang;
        Entities.ChiTietChinhSachGiaHangHoa[] chitiettempcheck;
        Entities.ChiTietChinhSachGiaHangHoa[] checklistview;

        DateTime date;

        #endregion

        #region frmXuLyChinhSachGiaHangHoa

        // Then add
        public frmXuLy(string hanhdong)
        {
            try
            {
                InitializeComponent();
                this.hanhdong = hanhdong;
                this.chitiettempcheck = HienThi();
                txtMaCSGHH.Text = getID();
           
                date = Common.StaticVariable.InterfaceObject.SelectDate();
                dpNgayBatDau.Text =Common.StaticVariable.InterfaceObject.SelectDate().Date.ToString();
                dpNgayKetThuc.Text = Common.StaticVariable.InterfaceObject.SelectDate().Date.ToString();

            }
            catch 
            {
            }
        }

        // then edit    
        public frmXuLy(Entities.ChinhSachGiaHangHoa chinhsachgiahang, Entities.ChinhSachGiaHangHoa[] tempcheck,string hanhdong)
        {
            try
            {
                InitializeComponent();
                this.hanhdong = hanhdong;
                date = Common.StaticVariable.InterfaceObject.SelectDate();
                // gan gia tri
                this.tempcheck = tempcheck;
                temp = chinhsachgiahang;

                this.tempcheck = tempcheck;
                this.chitiettempcheck = HienThi();
                if (chinhsachgiahang.GiaTriTrangThai == "Đã sử dụng" || chinhsachgiahang.GiaTriTrangThai == "Đang sử dụng")
                {
                    panel1.Enabled = false;
                    panel_ChiTiet.Enabled = false;
                    dgvHienThi.Enabled = false;
                    btnGhiLai.Enabled = false;
                }

                // hiển thị chi tiết
                chitietchinhsachgiahang = HienThiChiTiet(chinhsachgiahang);
                dgvHienThi.DataSource = chitietchinhsachgiahang;
                templv = chitietchinhsachgiahang;
                fix();
                XuLyDuLieu(chinhsachgiahang);
            
            }
            catch 
            {
            }
       
        }

        #endregion

        #region check permission
        public bool CheckPer()
        {
            return true;
        }
        #endregion

        #region Check conflicts

        string machinhsachgiahanghoa = "";
        // Check Conflic Insert
        public bool CheckConflicInsert()
        {
            try
            {
                Entities.GetID id = new Entities.GetID();
                id.TableName = "ChinhSachGiaHangHoa";
                Entities.GetID get = Common.StaticVariable.InterfaceObject.SelectID(id);

                machinhsachgiahanghoa = get.ColumnName;
                if (get.ColumnName == txtMaCSGHH.Text)
                {
                    return true;
                }
                return false;
            }
            catch { return false; }
        }

        // kiểm tra
        public bool kiemtra(Entities.ChinhSachGiaHangHoa csghh)
        {
            bool kt = true;
            if (temp.MaChinhSachGiaHangHoa != csghh.MaChinhSachGiaHangHoa)
            {
                txtMaCSGHH.Text = csghh.MaChinhSachGiaHangHoa;
                kt = false;
            }
         
            return kt;
        }

        #endregion

        #region Nghiệp vụ

        #region thoát
        public void Thoat()
        {
                checkClose = false;
                this.Close();
        }
        #endregion

        #region Sua

        void Sua()
        {
            try
            {
                if (btnGhiLai.Enabled == false)
                {
                    return;
                }
                if (check)
                {
                    check = false;
                    return;
                }
                chinhsachgiahanghoa = XuLyObject(Common.Constants.Update);
                chitietchinhsachgiahang = (Entities.ChiTietChinhSachGiaHangHoa[])dgvHienThi.DataSource;
                // check object
                if (chinhsachgiahanghoa == null)
                {
                    return;
                }

                // check conflic insert
                if (!CheckConflicUpdate())
                {
                    MessageBox.Show(Common.MSG.MSG6(), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    return;
                }
                if (checklistview == null || checklistview.Length == 0)
                {
                    MessageBox.Show("Hãy chọn chi tiết hàng hóa ?", Common.MSG.TieuDe);
                    txtSoLuong.Focus();
                    return;
                }
                // check insert
                if (!Common.StaticVariable.InterfaceObject.InsertUpdateChinhSachGiaHangHoa(chinhsachgiahanghoa))
                {
                    MessageBox.Show(Common.MSG.MSG15(chinhsachgiahanghoa.MaChinhSachGiaHangHoa), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    Common.StaticVariable.InterfaceObject.DeleteChinhSachGiaHangHoa(chinhsachgiahanghoa);
                    return;
                }
                // delete details
                Entities.ChiTietChinhSachGiaHangHoa delete = new Entities.ChiTietChinhSachGiaHangHoa();
                delete.MaChinhSachGiaHangHoa = chinhsachgiahanghoa.MaChinhSachGiaHangHoa;
                if (Common.StaticVariable.InterfaceObject.DeleteChiTietChinhSachGiaHangHoa(delete))
                {
                }
                // check insert details
                foreach (Entities.ChiTietChinhSachGiaHangHoa item in chitietchinhsachgiahang)
                {
                    item.HanhDong = Common.Constants.Insert;
                }
                if (!Common.StaticVariable.InterfaceObject.InsertUpdateChiTietChinhSachGiaHangHoa(chitietchinhsachgiahang))
                {
                    return;
                }

                checkClose = true;
                chinhsachgiahanghoa = null;
                check = true;
                this.Close();
            }
            catch
            {
            }
        }

        public bool CheckConflicUpdate()
        {
            try
            {
                Entities.ChinhSachGiaHangHoa[] mangchitiet = HienThi(date);
                for (int i = 0; i < mangchitiet.Length; i++)
                {
                    if (mangchitiet[i].MaChinhSachGiaHangHoa == temp.MaChinhSachGiaHangHoa)
                    {
                        return Check(mangchitiet[i]);
                    }
                }
                return true;
            }
            catch
            {
                return false;
            }
        }
        //
        public bool Check(Entities.ChinhSachGiaHangHoa khuyenmaitanghang)
        {
            bool kt = true;
            if (temp.Trangthai != khuyenmaitanghang.Trangthai)
            {
                kt = false;
            }
            return kt;
        }

        #endregion

        #region thêm
        public void Them()
        {
            try
            {
                if (btnGhiLai.Enabled == false)
                {
                    return;
                }
                if (check)
                {
                    check = false;
                    return;
                }

                chinhsachgiahanghoa = XuLyObject(Common.Constants.Insert);
                chitietchinhsachgiahang = (Entities.ChiTietChinhSachGiaHangHoa[])dgvHienThi.DataSource;
                //tempcheck = new HienThi(date);
                chitiettempcheck = HienThi();

                //// check hàng khuyến mại
                //if (!CheckChinhSachGiaHang())
                //{
                //    MessageBox.Show(Common.MSG.MSG24(txtMaHangHoa.Text, machinhsachgiahangtrung), Common.MSG.TieuDe, MessageBoxButtons.OK);
                //    return;
                //}
           
                // check object 
                if (chinhsachgiahanghoa == null)
                {
                    return;
                }

                //
                if (checklistview == null || checklistview.Length == 0)
                {
                    MessageBox.Show("Hãy chọn chi tiết hàng hóa ?", Common.MSG.TieuDe);
                    txtSoLuong.Focus();
                    return;
                }
                // check conflict insert
                if (CheckConflicInsert())
                {
                    MessageBox.Show(Common.MSG.MSG5(chinhsachgiahanghoa.MaChinhSachGiaHangHoa), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    txtMaCSGHH.Text = getID();

                    return;
                }
                else {}
                //check insert
                if (!Common.StaticVariable.InterfaceObject.InsertUpdateChinhSachGiaHangHoa(chinhsachgiahanghoa))
                {
                    return;
                }

                //
                Entities.ChiTietChinhSachGiaHangHoa[] listview = (Entities.ChiTietChinhSachGiaHangHoa[])dgvHienThi.DataSource;
                if (listview == null)
                {
                    return;
                }

                // check insert chi tiet chinh sach gia hang hoa
                Common.StaticVariable.InterfaceObject.InsertUpdateChiTietChinhSachGiaHangHoa(listview);
                
                checkClose = true;
                chinhsachgiahanghoa = null;
                check = true;
                this.Close();

            }
            catch
            {
            }

        }
        #endregion

        #endregion

        #region Event of Window

        private void frmXuLy_Load(object sender, EventArgs e)
        {
            try
            {
                btnThoat.MouseDown += new MouseEventHandler(MouseDown_Chung);
                btnGhiLai.MouseDown += new MouseEventHandler(MouseDown_Chung);
                lblTenNhanVien.Text = UtilitiesVariable.User.TenDangNhap;
      
            }
            catch 
            {
            }
    }

        private void Window_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                switch (e.KeyCode)
                {
                    case Keys.F2:
                        {
                            switch (hanhdong)
                            {
                                case Common.Constants.Insert:
                                    {
                                        checklistview = (Entities.ChiTietChinhSachGiaHangHoa[])dgvHienThi.DataSource;
                                        Them();
                                        break;
                                    }
                                case Common.Constants.Update:
                                    {
                                        checklistview = (Entities.ChiTietChinhSachGiaHangHoa[])dgvHienThi.DataSource;
                                        Sua();
                                        break;
                                    }
                            }

                            break;
                        }

                    case Keys.Escape:
                        {
                            Thoat();
                            break;
                        }

                }
            }
            catch 
            {
                
                
            }
     
        }

        private void Window_Closing(object sender, FormClosingEventArgs e)
        {
            try
            {
                if (!checkClose)
                    if (MessageBox.Show(Common.MSG.MSG2(), Common.MSG.TieuDe, MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        e.Cancel = checkClose;
                    }
                    else
                        e.Cancel = !checkClose;
                else
                {
                    if (!kiemtra1)
                         Select(hanhdong);
                     
                }

            }
            catch
            {
            }
        }

        public delegate void SelectData(string hanhdong);
        public SelectData Select;

        //
        public Entities.ChiTietChinhSachGiaHangHoa[] HienThi()
        {
            try
            {
                ArrayList array = new ArrayList();
                Entities.ChiTietChinhSachGiaHangHoa[] chitietchinhsachgiahang = Common.StaticVariable.InterfaceObject.SelectChiTietChinhSachGiaHangHoa();
                
                return chitietchinhsachgiahang;
            }
            catch { return new Entities.ChiTietChinhSachGiaHangHoa[0]; }
        }
        //
        public Entities.ChiTietChinhSachGiaHangHoa[] HienThiChiTiet(Entities.ChinhSachGiaHangHoa chinhsachgiahang)
        {
            try
            {
                ArrayList array = new ArrayList();
                Entities.ChiTietChinhSachGiaHangHoa[] temp = Common.StaticVariable.InterfaceObject.SelectChiTietChinhSachGiaHangHoa();               
                foreach (Entities.ChiTietChinhSachGiaHangHoa item in temp)
                {
                    if (item.MaChinhSachGiaHangHoa == chinhsachgiahang.MaChinhSachGiaHangHoa)
                        array.Add(item);
                }
                Entities.ChiTietChinhSachGiaHangHoa[] chitietchinhsachgiahang = (Entities.ChiTietChinhSachGiaHangHoa[])array.ToArray(typeof(Entities.ChiTietChinhSachGiaHangHoa));
                return chitietchinhsachgiahang;
            }
            catch { return new Entities.ChiTietChinhSachGiaHangHoa[0]; }
        }

        //

        public Entities.ChinhSachGiaHangHoa[] HienThi(DateTime datetime)
        {
            try
            {
                Entities.ChinhSachGiaHangHoa[] chinhsachgiahang = Common.StaticVariable.InterfaceObject.SelectChinhSachGiaHangHoa();
                Entities.ChinhSachGiaHangHoa[] temp = new Entities.ChinhSachGiaHangHoa[chinhsachgiahang.Length];
                int sl = 0;
                for (int i = 0; i < chinhsachgiahang.Length; i++)
                {
                    if (chinhsachgiahang[i].Deleted == false)
                    {
                        temp[sl] = chinhsachgiahang[i];
                        sl++;
                    }
                }
                chinhsachgiahang = new Entities.ChinhSachGiaHangHoa[sl];
                for (int i = 0; i < chinhsachgiahang.Length; i++)
                {
                    chinhsachgiahang[i] = temp[i];
                }

                foreach (Entities.ChinhSachGiaHangHoa item in chinhsachgiahang)
                {
                    if (datetime.Date > item.NgayKetThuc.Date)
                        item.GiaTriTrangThai = "Đã sử dụng";
                    else if (datetime.Date < item.NgayBatDau.Date)
                        item.GiaTriTrangThai = "Sẽ sử dụng";
                    else if (datetime.Date >= item.NgayBatDau.Date && datetime.Date <= item.NgayKetThuc.Date)
                        item.GiaTriTrangThai = "Đang sử dụng";

                }
               return chinhsachgiahang;

            }
            catch
            {
                return new Entities.ChinhSachGiaHangHoa[0];

            }
        }
        #endregion

        #region Hien thi listview

        public bool ValidateDataGrid()
        {
            try
            {
                if (txtMaHangHoa.Text == "" || txtMaHangHoa.Text == "<F4 - Tra ")
                {
                    MessageBox.Show(Common.MSG.MSG13(lbMaHangHoa.Text.ToString()), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    txtMaHangHoa.Focus();
                    return false;
                }
                if (txtTenHangHoa.Text == "")
                {
                    MessageBox.Show(Common.MSG.MSG13(lbTenHangHoa.Text.ToString()), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    txtTenHangHoa.Focus();
                    return false;
                }
                if (txtSoLuong.Text == "")
                {
                    MessageBox.Show(Common.MSG.MSG13(lbSoLuong.Text.ToString()), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    txtSoLuong.Focus();
                    return false;
                }

                if (txtptBanBuon.Text == "")
                {
                    MessageBox.Show(Common.MSG.MSG13(lbptbanbuon.Text.ToString()), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    txtptBanBuon.Focus();
                    return false;
                }
                if (txtptBanLe.Text == "")
                {
                    MessageBox.Show(Common.MSG.MSG13(lbptbanle.Text.ToString()), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    txtptBanLe.Focus();
                    return false;
                }
            }
            catch 
            {
                
                
            }


            return true;
        }

        public void Add_Gridview()
        {
            try
            {
                if (txtMaCSGHH.Text.Length == 0)
                {
                    MessageBox.Show(Common.MSG.MSG13(lbMaChinhSachHangHoa.Text.ToString()), Common.MSG.TieuDe);
                    txtMaCSGHH.Focus();
                    return;
                }
                if (Convert.ToDouble(txtptBanLe.Text) < 0)
                {
                    MessageBox.Show(Common.MSG.MSG13(lbptbanle.Text.ToString()), Common.MSG.TieuDe);
                    return;
                }
                if (ValidateDataGrid())
                {
                    if (txtptBanLe.Text != "")
                    {
                        mahanghoa = txtMaHangHoa.Text;
                        NewRow();
                        txtMaHangHoa.Focus();
                        txtMaHangHoa.Text = "";
                        txtTenHangHoa.Text = "";
                        txtSoLuong.Text = "1";
                        txtptBanBuon.Text = "0";
                        txtptBanLe.Text = "0";
                        txtMaHangHoa.Text = "<F4 - Tra cứu>";
                    }
                }
            }
            catch
            {
            }
        }

        public void txtptBanLe_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.Enter)
                {
                    Add_Gridview();
                }
            }
            catch { }
        }

        public void dgvHienThi_CellClick(object sender, EventArgs e)
        {
            try
            {
                for (int i = 0; i < templv.Length; i++)
                {
                    if (templv[i].MaChinhSachGiaHangHoa == dgvHienThi.CurrentRow.Cells["MaChinhSachGiaHangHoa"].Value.ToString())
                    {
                        save = templv[i];
                    }
                }
                txtMaHangHoa.Text = save.MaHangHoa;
                txtTenHangHoa.Text = save.TenHangHoa;
                txtSoLuong.Text =Convert.ToString(save.SoLuong);
                txtptBanBuon.Text = save.PhanTramGiaBanBuon;
                txtptBanLe.Text = save.PhanTramGiaBanLe;
            }
            catch 
            { 
            }
        }

        public void DeleteRow()
        {
            try
            {
                hienthi = (Entities.ChiTietChinhSachGiaHangHoa[])dgvHienThi.DataSource;
                // list view = null
                if (hienthi == null)
                    return;
                // obj = null
                if (save == null)
                    return;
                templv = new Entities.ChiTietChinhSachGiaHangHoa[hienthi.Length - 1];
                int sotang = 0;
                for (int j = 0; j < hienthi.Length; j++)
                {
                    if (hienthi[j].MaHangHoa != save.MaHangHoa)
                    {
                        templv[sotang] = new Entities.ChiTietChinhSachGiaHangHoa(Common.Constants.Insert, txtMaCSGHH.Text, hienthi[j].MaHangHoa,
                            hienthi[j].TenHangHoa, hienthi[j].SoLuong, hienthi[j].PhanTramGiaBanBuon, hienthi[j].PhanTramGiaBanLe, "", false);
                        sotang++;
                    }
                }
                dgvHienThi.DataSource = templv;
                //lblTongbanghi.Text = Common.Constants.TongSo + dgvHienThi.Items.Count;
                save = null;
            }
            catch 
            {
                
                
            }
  

        }

        public void dgvHienThi_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
              DeleteRow();
            }
            catch 
            { 
            }
        }

        string mahanghoa;
        public int soluongmoi;
        public int soluongcu;
        public int soluonghientai;

        public double ptbanbuonmoi;
        public double ptbanbuoncu;
        public double ptbanbuonhientai;

        public double ptbanlemoi;
        public double ptbanlecu;
        public double ptbanlehientai;

        Entities.ChiTietChinhSachGiaHangHoa[] hienthi;
        Entities.ChiTietChinhSachGiaHangHoa[] templv;
        Entities.ChiTietChinhSachGiaHangHoa save;

        public void NewRow()
        {
            try
            {
                int sohangtrongbang;
                hienthi = (Entities.ChiTietChinhSachGiaHangHoa[])dgvHienThi.DataSource;
                // check hàng khuyến mại
                //if (!CheckChinhSachGiaHang())
                //{
                //    MessageBox.Show(Common.MSG.MSG24(txtMaHangHoa.Text, machinhsachgiahangtrung), Common.MSG.TieuDe, MessageBoxButtons.OK);
                //    return;
                //}
                // list view = null
                if (hienthi == null)
                {
                    // pt ban le
                    string ptbanle = "0";
                    if (txtptBanLe.Text == "")
                        ptbanle = "0";
                    else
                        ptbanle = txtptBanLe.Text;
                    string giatriptbanle = ptbanle;

                    // pt ban buon
                    string ptbanbuon = "0";
                    if (txtptBanBuon.Text == "")
                        ptbanbuon = "0";
                    else
                        ptbanbuon = txtptBanBuon.Text;
                    string giatriptbanbuon = ptbanbuon;

                    // so luong
                    string soluong = "0";
                    if (txtSoLuong.Text == "")
                        soluong = "0";
                    else
                        soluong = txtSoLuong.Text;
                    string soluonghanghoa = soluong;


                    templv = new Entities.ChiTietChinhSachGiaHangHoa[1];

                    templv[0] = new Entities.ChiTietChinhSachGiaHangHoa(Common.Constants.Insert, txtMaCSGHH.Text, txtMaHangHoa.Text,
                        txtTenHangHoa.Text, int.Parse(soluong), ptbanbuon, ptbanle, "", false);
                    templv[0].MaChinhSachGiaHangHoa = txtMaCSGHH.Text.ToString();
                    dgvHienThi.DataSource = templv;
                    return;
                }

                sohangtrongbang = hienthi.Length;
                // số lượng bảng ghi khác 0
                if (sohangtrongbang != 0)
                {
                    for (int j = 0; j < sohangtrongbang; j++)
                    {
                        // nếu tìm được mã đã có trong list view
                        if (mahanghoa == hienthi[j].MaHangHoa)
                        {
                            templv = new Entities.ChiTietChinhSachGiaHangHoa[sohangtrongbang];
                            break;
                        }
                        // nếu không tìm được
                        else
                            templv = new Entities.ChiTietChinhSachGiaHangHoa[sohangtrongbang + 1];
                    }
                }
                // số lượng bảng ghi = 0
                else
                    templv = new Entities.ChiTietChinhSachGiaHangHoa[sohangtrongbang + 1];
                // nếu số lượng bảng ghi khác 0
                if (templv.Length != 0)
                {
                    try
                    {
                        // số lượng bảng ghi = số lượng row list view
                        if (templv.Length == hienthi.Length)
                        {
                            for (int j = 0; j < templv.Length; j++)
                            {
                                // nếu mã = mã trong list view
                                if (mahanghoa == hienthi[j].MaHangHoa)
                                {
                                    // cong don so luong
                                    soluongcu = hienthi[j].SoLuong;
                                    int soluong = 0;
                                    if (txtSoLuong.Text == "")
                                        soluong = 1;
                                    else
                                        soluong = int.Parse(txtSoLuong.Text);
                                    soluongmoi = soluong;
                                    soluonghientai = soluongcu + soluongmoi;

                                    // cong don phan tram ban buon
                                    ptbanbuoncu = double.Parse(hienthi[j].PhanTramGiaBanBuon);
                                    double ptbanbuon = 0;
                                    if (txtptBanBuon.Text == "")
                                        ptbanbuon = 1;
                                    else
                                        ptbanbuon = double.Parse(txtptBanBuon.Text);
                                    ptbanbuonmoi = ptbanbuon;
                                    ptbanbuonhientai = ptbanbuoncu + ptbanbuonmoi;

                                    // cong don so luong
                                    ptbanlecu = double.Parse(hienthi[j].PhanTramGiaBanLe);
                                    double ptbanle = 0;
                                    if (txtptBanLe.Text == "")
                                        ptbanle = 1;
                                    else
                                        ptbanle = double.Parse(txtptBanLe.Text);
                                    ptbanlemoi = ptbanle;
                                    ptbanlehientai = ptbanlecu + ptbanlemoi;



                                    templv[j] = new Entities.ChiTietChinhSachGiaHangHoa(Common.Constants.Insert, txtMaCSGHH.Text,
                                        txtMaHangHoa.Text, (txtTenHangHoa.Text), soluonghientai,
                                        Convert.ToString(ptbanbuonhientai), Convert.ToString(ptbanlehientai), "", false);
                                    templv[j].MaChinhSachGiaHangHoa = txtMaCSGHH.Text.ToString();
                                }
                                // nếu mã không = mã trong list view
                                else
                                {
                                    templv[j] = new Entities.ChiTietChinhSachGiaHangHoa(Common.Constants.Insert, txtMaCSGHH.Text, hienthi[j].MaHangHoa,
                                        hienthi[j].TenHangHoa, hienthi[j].SoLuong, hienthi[j].PhanTramGiaBanBuon, hienthi[j].PhanTramGiaBanLe, "", false);
                                    templv[j].MaChinhSachGiaHangHoa = txtMaCSGHH.Text.ToString();
                                }

                            }
                        }
                        // số lượng bảng ghi không = số lượng row list view
                        else
                        {
                            for (int j = 0; j < templv.Length; j++)
                            {
                                // lấy lại số bảng ghi trên list view
                                if (j < templv.Length - 1)
                                {
                                    templv[j] = new Entities.ChiTietChinhSachGiaHangHoa(Common.Constants.Insert, txtMaCSGHH.Text, hienthi[j].MaHangHoa,
                                        hienthi[j].TenHangHoa, hienthi[j].SoLuong, hienthi[j].PhanTramGiaBanBuon, hienthi[j].PhanTramGiaBanLe, "", false);
                                    templv[j].MaChinhSachGiaHangHoa = txtMaCSGHH.Text.ToString();
                                }
                                // bảng ghi cuối cùng là mới insert vào
                                else
                                {
                                    //
                                    string soluong = "0";
                                    if (txtSoLuong.Text == "")
                                        soluong = "1";
                                    else
                                        soluong = txtSoLuong.Text;
                                    string sl = soluong;

                                    //
                                    string ptbanle = "0";
                                    if (txtptBanLe.Text == "")
                                        ptbanle = "1";
                                    else
                                        ptbanle = txtptBanLe.Text;
                                    string ptbl = ptbanle;
                                    //
                                    string ptbanbuon = "0";
                                    if (txtptBanBuon.Text == "")
                                        ptbanbuon = "1";
                                    else
                                        ptbanbuon = txtptBanBuon.Text;
                                    string ptbb = ptbanbuon;


                                    templv[templv.Length - 1] = new Entities.ChiTietChinhSachGiaHangHoa(Common.Constants.Insert, txtMaCSGHH.Text, txtMaHangHoa.Text,
                                        txtTenHangHoa.Text, int.Parse(soluong), (ptbanbuon), (ptbanle), "", false);
                                    templv[j].MaChinhSachGiaHangHoa = txtMaCSGHH.Text.ToString();
                                }
                            }
                        }
                    }
                    catch
                    {
                        //
                        string soluong = "0";
                        if (txtSoLuong.Text == "")
                            soluong = "1";
                        else
                            soluong = txtSoLuong.Text;
                        string sl = soluong;

                        //
                        string ptbanle = "0";
                        if (txtptBanLe.Text == "")
                            ptbanle = "1";
                        else
                            ptbanle = txtptBanLe.Text;
                        string ptbl = ptbanle;
                        //
                        string ptbanbuon = "0";
                        if (txtptBanBuon.Text == "")
                            ptbanbuon = "1";
                        else
                            ptbanbuon = txtptBanBuon.Text;
                        string ptbb = ptbanbuon;


                        templv[templv.Length - 1] = new Entities.ChiTietChinhSachGiaHangHoa(Common.Constants.Insert, txtMaCSGHH.Text, txtMaHangHoa.Text,
                            txtTenHangHoa.Text, int.Parse(soluong), (ptbanbuon), (ptbanle), "", false);

                    }
                    dgvHienThi.DataSource = templv;

                }
            }
            catch
            {
                string ptbanle = "0";
                if (txtptBanLe.Text == "")
                    ptbanle = "1";
                else
                    ptbanle = txtptBanLe.Text;
                string soluongsp = ptbanle;
                templv = new Entities.ChiTietChinhSachGiaHangHoa[1];
                templv[0] = new Entities.ChiTietChinhSachGiaHangHoa(Common.Constants.Insert, txtMaCSGHH.Text,
                    txtMaHangHoa.Text, txtTenHangHoa.Text, int.Parse(txtSoLuong.Text),
                    (txtptBanBuon.Text), (ptbanle), "", false);

                dgvHienThi.DataSource = templv;
            }
            finally
            {
                fix();
            }
        }

        //
        void fix()
        {
            for (int i = 0; i < dgvHienThi.ColumnCount; i++)
            {
                dgvHienThi.Columns[i].Visible = false;
            }

            dgvHienThi.Columns["MaHangHoa"].HeaderText = "Mã Hàng Hóa";
            dgvHienThi.Columns["MaHangHoa"].Visible = true;
            dgvHienThi.Columns["TenHangHoa"].HeaderText = "Tên Hàng Hóa";
            dgvHienThi.Columns["TenHangHoa"].Visible = true;
            dgvHienThi.Columns["SoLuong"].HeaderText = "Số Lượng";
            dgvHienThi.Columns["SoLuong"].Visible = true;
            dgvHienThi.Columns["PhanTramGiaBanBuon"].HeaderText = "% Bán Buôn";
            dgvHienThi.Columns["PhanTramGiaBanBuon"].Visible = true;
            dgvHienThi.Columns["PhanTramGiaBanLe"].HeaderText = "% Bán Lẻ";
            dgvHienThi.Columns["PhanTramGiaBanLe"].Visible = true;
            if (dgvHienThi.RowCount > 0)
            {
                dgvHienThi.Focus();
                dgvHienThi.Select();
            }
            dgvHienThi.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dgvHienThi.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
        }
        //
        string machinhsachgiahangtrung = "";
        bool CheckChinhSachGiaHang()
        {
            try
            {
                foreach (Entities.ChinhSachGiaHangHoa item in tempcheck)
                {
                    if (item.GiaTriTrangThai == "Đã sử dụng" || item.GiaTriTrangThai == "Đang sử dụng" && item.MaChinhSachGiaHangHoa != temp.MaChinhSachGiaHangHoa)
                    {
                        // check chi tiết ở list view
                        if (chitietchinhsachgiahang != null)
                        {
                            foreach (Entities.ChiTietChinhSachGiaHangHoa item1 in chitietchinhsachgiahang)
                            {
                                if (item.MaChinhSachGiaHangHoa == item1.MaChinhSachGiaHangHoa)
                                {
                                    if (item1.MaHangHoa == txtMaHangHoa.Text && item1.SoLuong.ToString() != txtSoLuong.Text)
                                    {
                                        return false;
                                    }
                                }
                            }
                        }

                        // check chi tiết ở database
                        foreach (Entities.ChiTietChinhSachGiaHangHoa item1 in chitiettempcheck)
                        {
                            if (item.MaChinhSachGiaHangHoa == item1.MaChinhSachGiaHangHoa)
                            {
                                if (item1.MaHangHoa == txtMaHangHoa.Text && item1.SoLuong.ToString() != txtSoLuong.Text)
                                {
                                    machinhsachgiahanghoa = item1.MaChinhSachGiaHangHoa;
                                    return false;
                                }
                            }
                        }

                    }
                }
                return true;
            }
            catch
            {
                return false;

            }
        }

        #endregion

        #region Mouse Down Chung

        void MouseDown_Chung(object sender, MouseEventArgs e)
        {
            try
            {
                checklistview = (Entities.ChiTietChinhSachGiaHangHoa[])dgvHienThi.DataSource;
                Button img = (Button)sender;
                switch (img.Name)
                {
                    case Common.Constants.btnThoat:
                        {
                            Thoat();
                            break;
                        }
                    case Common.Constants.btnGhiLai:
                        {
                            if (hanhdong == Common.Constants.Insert)
                            {
                                Them();
                            }
                            if (hanhdong == Common.Constants.Update)
                            {
                                 Sua();
                            }
                            break;
                        }

                    default: break;
                }
            }
            catch 
            {
            }

        }

        #endregion

        #region Control Event
        public DateTime batdau, ketthuc;

        #region Thêm Hàng Hóa
        void ThemHangHoa()
        {
            try
            {
                TimKiem.frmHangHoa frm = new TimKiem.frmHangHoa("CSGHH", 23);
                frm.ShowDialog();
                if (TimKiem.frmHangHoa.selectedItemHH != null)
                {
                    {
                        txtMaHangHoa.Text = TimKiem.frmHangHoa.selectedItemHH.MaHangHoa;
                        txtTenHangHoa.Text = TimKiem.frmHangHoa.selectedItemHH.TenHangHoa;
                        txtSoLuong.Focus();
                    }
                }
            }
            catch
            {
            }
        }
        #endregion

        #region KeyDown

        private void txtMaKH_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                dpNgayBatDau.Focus();
            }
        }

        private void dpNgayBatDau_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                dpNgayBatDau.Focus();
            }
        }

        private void dpNgayKetThuc_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                txtMaCSGHH.Focus();
            }
        }

        private void txtMaHangHoa_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                txtTenHangHoa.Focus();
            }
            if (e.KeyCode == Keys.F4)
            {
                ThemHangHoa();
            }
        }

        private void txtTenHangHoa_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                txtSoLuong.Focus();
            }
          
        }

        private void txtSoLuong_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                txtptBanBuon.Focus();
            }
        }

        private void txtptBanBuon_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                txtptBanLe.Focus();
            }
        }

       
        #endregion

        #region xử lý ID
        public string getID()
        {
            string code = string.Empty;
            try
            {
                Entities.GetID id = new Entities.GetID();
                id.TableName = "ChinhSachGiaHangHoa";
                Entities.GetID get = Common.StaticVariable.InterfaceObject.SelectID(id);

                if (get.ColumnName != null)
                {
                    code = Common.Utilities.ProcessID(get.ColumnName);
                }
                else
                { code = "CSGHH_0001"; }
            }
            catch (Exception ex)
            {
                string s = ex.Message;
                code = "CSGHH_0001";
            }
            return code;
        }
        #endregion

        #region check validate

        public bool Validate()
        {
            try
            {
                if (txtMaCSGHH.Text == "")
                {
                    MessageBox.Show(Common.MSG.MSG13(lbMaChinhSachHangHoa.Text.ToString()), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    txtMaCSGHH.Focus();
                    return false;
                }

                if (dpNgayBatDau.Text == "")
                {
                    MessageBox.Show(Common.MSG.MSG13(lbNgayBatDau.Text.ToString()), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    dpNgayBatDau.Focus();
                    return false;
                }

                if (dpNgayKetThuc.Text == "")
                {
                    MessageBox.Show(Common.MSG.MSG13(lbNgayKetThuc.Text.ToString()), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    dpNgayKetThuc.Focus();
                    return false;
                }

                batdau = DateTime.Parse(dpNgayBatDau.Text);
                ketthuc = DateTime.Parse(dpNgayKetThuc.Text);

                if (batdau.Date < Common.StaticVariable.InterfaceObject.SelectDate().Date)
                {
                    MessageBox.Show(Common.MSG.MSG13("Ngày bắt đầu lớn hơn hoặc bằng ngày hiện tại"), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    dpNgayBatDau.Text = "";
                    dpNgayBatDau.Focus();
                    return false;
                }

                if (ketthuc < batdau)
                {
                    MessageBox.Show(Common.MSG.MSG13("Ngày kết thúc lớn hơn hoặc bằng ngày bắt đầu"), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    dpNgayKetThuc.Text = "";
                    dpNgayBatDau.Focus();
                    return false;
                }
                return true;
            }
            catch
            {
                return true;
            }
        }

        #endregion

        #region Xu ly object

        public void XuLyDuLieu(Entities.ChinhSachGiaHangHoa chinhsachgiahanghoa)
        {
            try
            {
                txtMaCSGHH.Text = chinhsachgiahanghoa.MaChinhSachGiaHangHoa;
                dpNgayBatDau.Text =chinhsachgiahanghoa.NgayBatDau.ToString();
                dpNgayKetThuc.Text = chinhsachgiahanghoa.NgayKetThuc.ToString();
            }
            catch { }
        }

        // Insert data of phiếu thanh toán khách hàng into database
        public Entities.ChinhSachGiaHangHoa XuLyObject(string hanhdong)
        {
            try
            {
                if (Validate())
                {
                    Entities.ChinhSachGiaHangHoa chinhsachgiahanghoa = new Entities.ChinhSachGiaHangHoa();
                    chinhsachgiahanghoa.HanhDong = hanhdong;
                    chinhsachgiahanghoa.MaChinhSachGiaHangHoa = txtMaCSGHH.Text.ToString();
                    chinhsachgiahanghoa.NgayBatDau =DateTime.Parse(dpNgayBatDau.Text);
                    chinhsachgiahanghoa.NgayKetThuc =DateTime.Parse(dpNgayKetThuc.Text);
                    chinhsachgiahanghoa.NgayLap = date.Date;
                    chinhsachgiahanghoa.GhiChu = "";
                    chinhsachgiahanghoa.Deleted = false;
                    chinhsachgiahanghoa.TaiKhoan = UtilitiesVariable.User;
                    return chinhsachgiahanghoa;
                }
                return null;
            }
            catch
            {
                return null;
            }

        }

        #endregion

        #region Xu ly du lieu nhap

        private void txtptbanbuon_TextChanged(object sender, EventArgs e)
        {
                    try
                    {
                        string ptbanbuon = txtptBanBuon.Text;
                        if (double.Parse(ptbanbuon) < 0 || double.Parse(ptbanbuon) > 100)
                        {
                            txtptBanBuon.Text = "";
                        }
                    }
                    catch
                    {
                    }
                    TextBox temp = (TextBox)sender;
                    int vt = temp.SelectionStart;
                    string str = new string(temp.Text.ToList<char>().Where(c => char.IsNumber(c)).ToArray<char>());
                    temp.Text = str;
                    temp.SelectionStart = vt;

        }

        private void txtptbanle_TextChanged(object sender, EventArgs e)
        {

            try
            {
                string ptbanle = txtptBanLe.Text;
                if (double.Parse(ptbanle) < 0 || double.Parse(ptbanle) > 100)
                {
                    txtptBanLe.Text = "";
                }
            }
            catch { }

                    TextBox temp = (TextBox)sender;
                    int vt = temp.SelectionStart;
                    string str = new string(temp.Text.ToList<char>().Where(c => char.IsNumber(c)).ToArray<char>());
                    temp.Text = str;
                    temp.SelectionStart = vt;
      
        }

        private void txtSoLuong_TextChanged(object sender, EventArgs e)
        {
            TextBox temp = (TextBox)sender;
            int vt = temp.SelectionStart;
            string str = new string(temp.Text.ToList<char>().Where(c => char.IsNumber(c)).ToArray<char>());
            temp.Text = str;
            temp.SelectionStart = vt;
        }

        #endregion

        private void txtMaHangHoa_MouseLeave(object sender, EventArgs e)
        {
            if (txtMaHangHoa.Text == "")
            {
                txtMaHangHoa.Text = "<F4 - Tra cứu>";
            }
        }

        private void txtMaHangHoa_MouseMove(object sender, MouseEventArgs e)
        {
            if (txtMaHangHoa.Text == "<F4 - Tra cứu>")
            {
                txtMaHangHoa.Text = "";
            }
        }

        private void btnThem_Click(object sender, EventArgs e)
        {
            Add_Gridview();
        }

        #endregion


    }
}
